package com.ecommerce.dal.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.ecommerce.dal.dao.IUserDAO;
import com.ecommerce.dal.entity.User;
import com.ecommerce.dal.util.CustomHibernateDAOSupport;

/**
 * @author XPPRESP3
 * 
 */
@Repository("userDAO")
public class UserDAO extends CustomHibernateDAOSupport implements IUserDAO {

	@Override
	public void save(User user) {
		getHibernateTemplate().save(user);
	}

	@Override
	public void update(User user) {
		getHibernateTemplate().update(user);
	}

	@Override
	public void delete(User user) {
		getHibernateTemplate().delete(user);
	}
	
	
	@Override
	public User findByUserId(long userId) {
		List list = getHibernateTemplate().find(
				//"select user from User user join  user.customer customer join user.client client join user.admin admin where user.userId = ?" , userId);
				"from User user where userId=?" , userId);
		return (User) ((list != null && list.size()>0) ?  list.get(0) : null) ;
	}

	@Override
	public User findByUserUsername(String username) {
		List list = getHibernateTemplate().find(
				"from User user where userName=?", username);
		return (User) ((list != null && list.size()>0) ?  list.get(0) : null) ;
	}

	@Override
	public User findByUserVerified(String username, String password) {
		List list = getHibernateTemplate().find(
				"from User user where userName=? and password=?",
				username, password);
		return (User) ((list != null && list.size()>0) ?  list.get(0) : null) ;
	}

	/*
	 * check to see if userId already exists in the system or valid user return
	 * true if already in the system , false otherwise
	 */
	public boolean checkUserIdIfExists(long userId) {
		List list = getHibernateTemplate().find(
				"select count(user) from User user where user.userId = ?",
				userId);
		return !((Long) (list.get(0))).equals(Long.valueOf(0)) ? true : false;
	}

	/*
	 * check to see if userName already exists in the system or valid user
	 * return true if already in the system , false otherwise
	 */
	public boolean checkUserNameIfExists(String userName) {
		List list = getHibernateTemplate().find(
				"select count(user) from User user where user.userName = ?",
				userName);
		return !((Long) (list.get(0))).equals(Long.valueOf(0)) ? true : false;

	}

	@Override
	public List<User> findAllUsers() {
		List list = getHibernateTemplate().find("from User");
		return ((list != null && list.size()>0) ?  list : null) ;
	}

	@Override
	public List<User> findNewsletterUsers() {
		List list = getHibernateTemplate().find(
				"from User user where user.newsletter = true");
		return ((list != null && list.size()>0) ?  list : null) ;
	}

}
